package com.shanghaionstar.nav;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.BounceInterpolator;
import android.view.animation.Interpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.Projection;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.LatLngBounds;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.VisibleRegion;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.map.OMapView;
import com.onstar.cn.map.common.LocationType;
import com.onstar.cn.weight.CustomButton;
import com.onstar.cn.weight.ToastView;
import com.shanghaionstar.R;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.nav.iview.INavMyFootPrintView;
import com.shanghaionstar.nav.model.FootPrintMapOperation;
import com.shanghaionstar.nav.model.FootPrintModel;
import com.shanghaionstar.nav.presenter.NavFootPrintPresenter;
import com.shanghaionstar.nav.service.AbstractMapActivity;
import com.shanghaionstar.nav.share.ShareFootPrintDialog;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.MapHandler;
import com.shanghaionstar.weight.TopLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 6335yz on 2016/7/25.
 * 我的足迹界面
 */
public class NavMyFootPrintFragment extends BaseFragment implements INavMyFootPrintView, AMap.InfoWindowAdapter, AMap.OnMarkerClickListener, View.OnClickListener {
    @FindViewById
    private OMapView mapview;
    private AMap aMap;
    private AbstractMapActivity mapActivity;
    private MapHandler mapHandler;
    private NavFootPrintPresenter navFootPrintPresenter;
    private UiSettings mUiSettings;
    private List<FootPrintModel> pois = new ArrayList<>();
    private List<FootPrintModel> showCityPois = new ArrayList<>();
    private VisibleRegion visibleRegion;
    private Projection projection;
    private LatLngBounds latLngBounds;
    @FindViewById
    private TopLayout top_layout;
    @FindViewById
    private LinearLayout bottom;
    private static final int START_SET_COLOR = 9;

    @FindViewById
    private TextView poicount, rank, title, bottom_title;
    @FindViewById
    private Button test, share;
    /**
     * 信息窗口view
     */
    private View view;
    private CustomButton delete;
    /**
     * flag信息窗口
     */
    private ImageView detail;
    private TextView flag_poi_count, flag_poi_city_name;


    /**
     * 这个变量逻辑上不可变，在第一次拿到所有城市的概略点后，保持不变。
     */
    private List<FootPrintModel> currentFootPrints;


    /**
     * 城市概略点在地图的可视区内内显示的列表
     */
    private List<String> lastTimeShowCitys = new ArrayList<String>();

    /**
     * 用于概略和详细poi切换
     */
    private boolean isSummaryShow = true;
    /**
     * 当前选中的足迹
     */
    private Marker currentMarker;

    private ProgressDialog progressDialog;

    @Override
    public int getLayoutId() {
        return R.layout.nav_footprint;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mapActivity = (AbstractMapActivity) activity;
    }

    private void enableShare(Boolean enable) {
        share.setEnabled(enable);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (isFirstLoad()) {
            enableShare(false);
            mapview.onCreate(savedInstanceState);
            aMap = mapview.getMap();
            mapHandler = new MapHandler(mapActivity, mapview.getMap());
            mapHandler.setTraffic(false);//关闭路况
            mapActivity.initMapHandler(mapHandler);
            navFootPrintPresenter = new NavFootPrintPresenter(mapActivity.getScheduler(), mapActivity, mapHandler);
            navFootPrintPresenter.setView(this);
            initMapSetting();
            monitorPoiInRect();
            top_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    goBack();
                }
            });
//            test.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    count++;
//                    showAnimatorBottomView(count % 2 == 0);
//                }
//            });
        }
    }

    /**
     * 初始化地图的设置信息
     */
    public void initMapSetting() {
        mUiSettings = aMap.getUiSettings();
        //隐藏地图自带的缩放控件
        mUiSettings.setZoomControlsEnabled(false);
        //设置可通过手势缩放
        mUiSettings.setZoomGesturesEnabled(true);
        //指南针
        mUiSettings.setCompassEnabled(false);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(4));
        aMap.setOnMarkerClickListener(this);
        aMap.setInfoWindowAdapter(this);
    }

    @Override
    public void onStart() {
        super.onStart();
//        showLoading();
//        navFootPrintPresenter.doGetPoiSummary();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
//        if(isVisibleToUser) {
//            showLoading();
//            navFootPrintPresenter.doGetPoiSummary();
//        }
    }

    private void showLoading() {
        if (progressDialog == null) {
            progressDialog = showLoadProgress();
        }
        progressDialog.show();
    }

    @Override
    public void onResumeView(View view) {
        super.onResumeView(view);
        //第一次进来进行提示

//        showAnimatorBottomView(false);
    }

    /**
     * 显示概略点
     */
    @Override
    public void showAllCityPoi(List<FootPrintModel> footPrintModels, boolean moveToRegion) {
        dismissDialog(progressDialog);
        if (aMap != null) {
//            showAnimatorBottomView(true);
            aMap.clear();
            currentFootPrints = footPrintModels;
            showPoiMarkersInMap(footPrintModels, FootPrintMapOperation.SHOW_ALL_SUMMARY);
            if (moveToRegion) {
                moveToRegion(footPrintModels, 100);
            }
            if (summaryZoom == 0)
                summaryZoom = aMap.getCameraPosition().zoom;
        }
    }

    /**
     * 在地图上显示marker点
     */
    private void showPoiMarkersInMap(List<FootPrintModel> footPrintModels, FootPrintMapOperation operation) {
        if (footPrintModels == null || footPrintModels.size() == 0) return;
        switch (operation) {
            case SHOW_ALL_SUMMARY:
            case SHOW_SUMMARY_WINDOW_INFO:
                for (int i = 0; i < footPrintModels.size(); i++) {
                    mapHandler.addFlagMarker(footPrintModels.get(i));
                }
                break;
            case SHOW_CITY_POIS:
                for (int i = 0; i < footPrintModels.size(); i++) {
                    mapHandler.addMarker(footPrintModels.get(i));
                }
                break;
        }
    }

    /**
     * 显示城市内详细足迹点
     */
    @Override
    public void showCityPoi(List<FootPrintModel> footPrintModels, FootPrintMapOperation operation) {
        this.showCityPois = footPrintModels;
        if (aMap != null) {
            aMap.clear();
            showPoiMarkersInMap(footPrintModels, operation);
            moveToRegion(footPrintModels, 100);
        }
    }

    private void moveToRegion(List<FootPrintModel> footPrintModels, int margin) {
        if (footPrintModels == null || footPrintModels.isEmpty())
            return;
        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        for (FootPrintModel model : footPrintModels) {
            builder.include(model.latLng);
        }
        LatLngBounds bounds = builder.build();
        // 移动地图，所有latlng自适应显示。LatLngBounds与地图边缘50像素的填充区域
        aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, CommonUtil.dp2px(30, baseActivity)), 800l, null);
    }

    @Override
    public void showSummaryWindowInfo(Marker marker, FootPrintModel footPrintModel) {
        marker.setObject(footPrintModel);
        if (footPrintModel != null) {
            jumpPoint(marker, footPrintModel.latLng);
        }
        marker.showInfoWindow();
    }

    /**
     * 计算可视区域内的城市概略点数量
     */
    private List<String> getLatLngCountInBounds(LatLngBounds bounds, List<FootPrintModel> currentFootPrints) {
        List<String> currentCitys = new ArrayList<String>();
        if (currentFootPrints == null || currentFootPrints.size() == 0) return null;
        for (FootPrintModel footPrintModel : currentFootPrints) {
            if (bounds.contains(footPrintModel.latLng)) {
                currentCitys.add(footPrintModel.seqId);
            }
        }
        return currentCitys;
    }

    private CameraPosition currentCenter;

    /**
     * 监听可视区域概略点的数量变换，用来显示详细足迹or概略足迹
     */
    private void monitorPoiInRect() {
        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
//                currentCenter = cameraPosition;
//                LatLng choosLatLng = null;
//                List<String> currentCitys = new ArrayList<String>();
//                visibleRegion = aMap.getProjection().getVisibleRegion();
//                latLngBounds = visibleRegion.latLngBounds;
//                currentCitys = getLatLngCountInBounds(latLngBounds, currentFootPrints);
//                if (currentCitys == null) return;
//                switch (currentCitys.size()) {
//                    case 0:
//                        isSummaryShow = false;
//                        break;
//                    case 1:
//                        isSummaryShow = false;
//                        if (!currentCitys.equals(lastTimeShowCitys)) {
//                            if (aMap != null) {
//                                aMap.clear();
//                            }
//                            navFootPrintPresenter.getCurrentShowCityPois(currentCitys.get(0), FootPrintMapOperation.SHOW_CITY_POIS);
//                        }
//                        break;
//                    default://多个城市显示概略点
//                        if (!currentCitys.equals(lastTimeShowCitys)) {
//                            if (aMap != null) {
//                                isSummaryShow = true;
////                                navFootPrintPresenter.showCityPoiByLtns(currentCitys);
//                                navFootPrintPresenter.showSummaryBottom();
//                                showAllCityPoi(currentFootPrints,false);
//                            }
//                        }
//                }
//                lastTimeShowCitys = currentCitys;
            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                currentCenter = cameraPosition;
                LatLng choosLatLng = null;
                List<String> currentCitys = new ArrayList<String>();
                visibleRegion = aMap.getProjection().getVisibleRegion();
                latLngBounds = visibleRegion.latLngBounds;
                currentCitys = getLatLngCountInBounds(latLngBounds, currentFootPrints);
                if (currentCitys == null) {
                    log.d("currentCitys is null");
                    return;
                }
                log.d("currentCitys.size = " + currentCitys.size());
                log.d("isSummaryShow = " + isSummaryShow);
                log.d("summaryZoom = " + summaryZoom + "cameraPosition.zoom" + cameraPosition.zoom);
                if (summaryZoom - cameraPosition.zoom > 0.5 && !isSummaryShow) {   //未显示概览时候，当概览缩放系数比视图缩放系数大1的时候显示概览
                    if (aMap != null) {
                        log.d("show summary...");
                        isSummaryShow = true;
//                                navFootPrintPresenter.showCityPoiByLtns(currentCitys);
                        navFootPrintPresenter.showSummaryBottom();
                        showAllCityPoi(currentFootPrints, false);
                    }
                } else if (cameraPosition.zoom - summaryZoom > 0.5 && isSummaryShow) {  //显示概览的时候继续放大，当视图缩放系数比概览缩放系数大于1的时候，则显示详细
                    isSummaryShow = false;
                    if (aMap != null) {
                        aMap.clear();
                    }
                    navFootPrintPresenter.getCurrentShowCityPois(currentCitys.get(0), FootPrintMapOperation.SHOW_CITY_POIS);
                }
            }
        });
    }

    private float summaryZoom = 0;

    @Override
    public View getInfoWindow(final Marker marker) {
        if (isSummaryShow) {
            view = LayoutInflater.from(mapActivity).inflate(R.layout.nav_footprint_flag_window, null);
            renderFlag(marker, view);
        } else {
            view = LayoutInflater.from(mapActivity).inflate(R.layout.nav_footprint_pop_window, null);
            render(marker, view);
        }
        return view;
    }

    /**
     * 详细足迹点的信息窗口展示
     */
    private void render(final Marker marker, View view) {
        delete = (CustomButton) view.findViewById(R.id.delete);
        title = (TextView) view.findViewById(R.id.title);
//        title.setText(marker.getTitle());
        FootPrintModel footPrintModel = (FootPrintModel) marker.getObject();
        title.setText(footPrintModel.destStreetName);
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialogUtil.showAlertDialog(baseActivity, getString(R.string.dialog_warning),
                        getString(R.string.nav_foot_print_dialog_question), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Footprint_DeleteFootprint.getStringValue());
                                navFootPrintPresenter.deleteCityPoi(marker, marker.getSnippet());
                            }
                        });
            }
        });
    }

    /**
     * 概略足迹点的信息窗口展示
     */
    private void renderFlag(final Marker marker, View view) {
        FootPrintModel footPrintModel = (FootPrintModel) marker.getObject();
        flag_poi_count = (TextView) view.findViewById(R.id.flag_poi_count);
        flag_poi_city_name = (TextView) view.findViewById(R.id.flag_poi_city_name);
        detail = (ImageView) view.findViewById(R.id.detail);
        if (footPrintModel != null) {
            flag_poi_city_name.setText(footPrintModel.cityName);
            flag_poi_count.setText(footPrintModel.poiCount + getString(R.string.nav_foot_print_pois));
        }
        detail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isSummaryShow = false;
                navFootPrintPresenter.getCurrentShowCityPois(marker.getSnippet(), FootPrintMapOperation.SHOW_CITY_POIS);
            }
        });
        flag_poi_city_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isSummaryShow = false;
                navFootPrintPresenter.getCurrentShowCityPois(marker.getSnippet(), FootPrintMapOperation.SHOW_CITY_POIS);
            }
        });
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        if (marker == currentMarker) return false;
        log.i("当前点击的marker" + marker.getPosition());
        currentMarker = marker;
        FootPrintModel footPrintModel = (FootPrintModel) marker.getObject();
        if (footPrintModel != null && footPrintModel.isLastPoint) {
            navFootPrintPresenter.getSummaryCityPois(marker, marker.getSnippet());
        } else {
            navFootPrintPresenter.getPoiDetail(marker.getPosition(), marker);
        }
        return false;
    }

    /**
     * marker点击时跳动一下
     */
    public void jumpPoint(final Marker marker, final LatLng latLng) {
        log.i("当前跳动的marker" + latLng);
        final Handler handler = new Handler();
        final long start = SystemClock.uptimeMillis();
        Projection proj = aMap.getProjection();
        Point startPoint = proj.toScreenLocation(latLng);
        startPoint.offset(0, -100);
        final LatLng startLatLng = proj.fromScreenLocation(startPoint);
        final long duration = 1500;

        final Interpolator interpolator = new BounceInterpolator();
        handler.post(new Runnable() {
            @Override
            public void run() {
                long elapsed = SystemClock.uptimeMillis() - start;
                float t = interpolator.getInterpolation((float) elapsed
                        / duration);
                double lng = t * latLng.longitude + (1 - t)
                        * startLatLng.longitude;
                double lat = t * latLng.latitude + (1 - t)
                        * startLatLng.latitude;
                marker.setPosition(new LatLng(lat, lng));
                aMap.invalidate();// 刷新地图
                if (t < 1.0) {
                    handler.postDelayed(this, 16);
                }
            }
        });
    }

    /**
     * 显示详细足迹点信息窗口
     */
    @Override
    public void showPopWindowInfo(Marker currentMarker, LatLng latLng) {
        if (latLng != null) {
            jumpPoint(currentMarker, latLng);
        }
        currentMarker.showInfoWindow();
    }

    /**
     * 底部足迹信息
     */
    @Override
    public void showBottomMsg(FootPrintModel footPrintModel) {
        dismissDialog(progressDialog);
        enableShare(true);
        if (!CommonUtil.isNull(footPrintModel.title)) {
            bottom_title.setText(footPrintModel.title);
        }
        if (!CommonUtil.isNull(footPrintModel.poiCount)) {
            poicount.setText(footPrintModel.poiCount);
        }
        if (!CommonUtil.isNull(footPrintModel.rank)) {
            SpannableString msp = new SpannableString(getString(R.string.nav_foot_print_rank, footPrintModel.rank));
            msp.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_107EDF)), START_SET_COLOR, START_SET_COLOR + footPrintModel.rank.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            msp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), START_SET_COLOR, START_SET_COLOR + footPrintModel.rank.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            rank.setText(msp);
        }
    }

    @OnClick({R.id.share})
    @Override
    public void onClick(View v) {
        BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Footprint_Share.getStringValue());
        showLoading();
        if (isSummaryShow)
            navFootPrintPresenter.loadOverViewShareUrl(String.valueOf(currentCenter.target.longitude), String.valueOf(currentCenter.target.latitude));
        else {
            if (showCityPois != null && !showCityPois.isEmpty())
                navFootPrintPresenter.loadDetailShareUrl(
                        String.valueOf(currentCenter.target.longitude), String.valueOf(currentCenter.target.latitude),
                        showCityPois.get(0).cityName,
                        String.valueOf(currentCenter.zoom));
        }
    }

    ShareFootPrintDialog shareDialog;
    String shareUrl;

    @Override
    public void showShareDialog(String shareUrl) {
        dismissDialog(progressDialog);
        this.shareUrl = shareUrl;
        if (shareDialog == null) {
            shareDialog = new ShareFootPrintDialog(mapActivity,
                    R.style.ShareDialog);
            Window window = shareDialog.getWindow();
            window.setGravity(Gravity.BOTTOM);  //此处可以设置dialog显示的位置
            window.setWindowAnimations(R.style.ShareDialog_Animation);  //添加动画
            shareDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
//                    dimBackground(0.5f, 1f);
                }
            });
        }
        String title = getResources().getString(R.string.onstar_myfootprints);
        String content = rank.getText().toString().trim();
        if (content.contains("您的"))
            content = content.replace("您的", "我的");
        shareDialog.setTitle(title);
        shareDialog.setContent(content);
        shareDialog.setUrl(shareUrl);
//        dimBackground(1f, 0.5f);
        shareDialog.show();
    }

    @Override
    public void showLoadShareUrlErr(Throwable throwable) {
        dismissDialog(progressDialog);
        new ToastView(mapActivity).showToast("获取分享信息失败");
    }

    @Override
    public void setLoading(boolean isLoading) {

    }

    @Override
    public void onResponseError(OnStarException e) {

    }

    @Override
    public void onReponseSuccess(Object object) {

    }


    @Override
    public void onResume() {
        super.onResume();
        mapview.onResume();
        if (showCityPois == null || showCityPois.isEmpty()) {
            showLoading();
            navFootPrintPresenter.doGetPoiSummary();
        }

        if (!PreferencesUtls.getInstance(mapActivity).getBoolean(Constants.FOOT_PRINT_TOAST, false)) {
            ToastView toastView = new ToastView(mapActivity);
            toastView.showFootToast(R.string.foot_print_toast, false);
            PreferencesUtls.getInstance(mapActivity).putBoolean(Constants.FOOT_PRINT_TOAST, true);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapview.onDestroy();
        if (navFootPrintPresenter != null) {
            navFootPrintPresenter.unsubscribe();
            navFootPrintPresenter = null;
        }
    }

    @Override
    public Activity onActivity() {
        return null;
    }

    /**
     * 删除后重新请求足迹数据
     *
     * @param isSuccess
     * @param marker
     */
    @Override
    public void showDeletePoiCallBackMsg(boolean isSuccess, Marker marker) {
        if (isSuccess) {
            marker.hideInfoWindow();
            marker.remove();
            marker.destroy();
            aMap.invalidate();
            navFootPrintPresenter.doGetPoiSummary();
            new ToastView(mapActivity).showToast(mapActivity.getString(R.string.nav_foot_print_dialog_result));
        } else {
            new ToastView(mapActivity).showToast(mapActivity.getString(R.string.nav_foot_print_dialog_result_fail));
        }
    }


    private void showAnimatorBottomView(boolean isShow) {
        if (isShow) {
            ObjectAnimator animator = ObjectAnimator.ofFloat(bottom, "translationY", bottom.getTranslationY(), 0);
            animator.setDuration(400);
            animator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationStart(Animator animation) {
                    bottom.setVisibility(View.VISIBLE);
                }
            });
            animator.start();
        } else {
            ObjectAnimator animator = ObjectAnimator.ofFloat(bottom, "translationY", bottom.getTranslationY(), bottom.getHeight());
            animator.setDuration(400);
            animator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationStart(Animator animation) {
                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    bottom.setVisibility(View.GONE);
                }
            });
            animator.start();
        }
    }

    @Override
    public void showNoPoi() {
        dismissDialog(progressDialog);
        AlertDialogUtil.showAlertDialog(baseActivity, getString(R.string.dialog_warning),
                getString(R.string.nav_foot_print_no_pois), false, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        mapActivity.showFragment(mapActivity.getSupportFragmentManager(),NavMapFragment.class,getClass());
                        mapActivity.showPoiToMap(mapActivity.getNavDataHolder().getMyPoi(), LocationType.MYSELF);
                    }
                });
    }

    @Override
    public void showErr(Throwable throwable) {
        dismissDialog(progressDialog);
        if (throwable != null && !TextUtils.isEmpty(throwable.getMessage()))
            new ToastView(mapActivity).showToast(throwable.getMessage());
    }

    /**
     * 调整窗口的透明度
     *
     * @param from>=0&&from<=1.0f
     * @param to>=0&&to<=1.0f
     */
    private void dimBackground(final float from, final float to) {
        final Window window = mapActivity.getWindow();
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(from, to);
        valueAnimator.setDuration(500);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                WindowManager.LayoutParams params = window.getAttributes();
                params.alpha = (Float) animation.getAnimatedValue();
                window.setAttributes(params);
            }
        });
        valueAnimator.start();
    }
}
